package com.my.designPattern_old;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * 通过反射机制修改单例模式的私有构造器，从而创建新的实例
 */
public class SingletonTest {

    public static void main(String[] args) {

        Singleton singleton = Singleton.getSingleton();
        System.out.println("name=======" + singleton.getName());
        Class clazz = Singleton.class;
        /**
         * 获取属性
         */
        Field [] fields = clazz.getDeclaredFields();
        for(int i =0;i < fields.length;i++){
            System.out.println(fields[i].getName() + "====" + fields[i].getType());
        }
        /**
         * 获取类的构造器
         */
        Constructor<Singleton> [] constructors = clazz.getDeclaredConstructors();
        System.out.println("==========" + constructors.length);
        for(int i =0;i < constructors.length;i++){
            //获取访问权限
            System.out.println(constructors[i]);
            System.out.println(Modifier.toString(constructors[i].getModifiers()));
            System.out.println(constructors[i].getName());
            constructors[i].setAccessible(true);
            //通过反射机制修改类的私有构造器，产生新的类
            try{
                Singleton singleton1 = (Singleton) constructors[i].newInstance("zhonglinxia");
                System.out.println(singleton1.getName());
            }catch (Exception e){
                System.out.println("=======================");
            }
        }

    }
}
